package com.fwj.core.common.common;

import com.fwj.core.common.constant.CoreConstant;
import com.fwj.core.common.execption.CommonException;
import com.fwj.core.common.model.JavaMailSenderVo;
import com.fwj.core.common.model.Mail;
import com.fwj.core.common.model.ResponseEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Author: fwj
 * @Data: 2022/5/3 2:30
 * @Version 1.0
 * @Description:    邮件发送工具
 */
public class MailUtil {


    //添加日志工厂
    private static final Logger LOGGER = LoggerFactory.getLogger(MailUtil.class);

    private static String config = "config";

    /**
     * 默认邮箱
     */
    private static String USERNAME = PropertiesFileUtil.getInstance(config).get("spring.mail.username");

    /**
     * 默认授权码
     */
    private static String PASSWORD = PropertiesFileUtil.getInstance(config).get("spring.mail.password");

    /**
     * 默认邮件协议
     */
    private static String PROTOCOL = PropertiesFileUtil.getInstance(config).get("spring.mail.protocol");

    /**
     * 默认编码格式
     */
    private static String DEFAULT_ENCODING = PropertiesFileUtil.getInstance(config).get("spring.mail.default-encoding");

    /**
     * 默认服务器
     */
    private static String HOST = PropertiesFileUtil.getInstance(config).get("spring.mail.host");

    /**
     * 默认端口号
     */
    private static String PORT = PropertiesFileUtil.getInstance(config).get("spring.mail.port");


    private static MimeMessage buildMessage(JavaMailSenderImpl mailSender){
        MimeMessage message = mailSender.createMimeMessage();
        return message;
    }

    private static MimeMessageHelper buildMail(MimeMessage message,Mail mail){

        MimeMessageHelper helper = null;
        try {
            //true表示支持复杂邮件
            helper = new MimeMessageHelper(message,true);
            //配置发件人
            helper.setFrom(mail.getFrom());
            //配置收件人
            helper.setTo(mail.getTo());
            //配置邮件主题
            helper.setSubject(mail.getSubject());
            //配置邮件正文
            helper.setText(mail.getText());
            //配置邮件附件
            if (CommonUtils.isNotEmpty(mail.getFiles())){
                for (MultipartFile file : mail.getFiles()){
                    helper.addAttachment(file.getOriginalFilename(),file);
                }
            }
            return helper;
        } catch (MessagingException e) {
            LOGGER.error(e.toString());
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        }
    }

    public static void sendMail(Mail mail){
        JavaMailSenderImpl mailSender = null;
        try {
            //设置默认发件人
            mail.setFrom(USERNAME);
            mailSender = buildJavaMailSenderImpl();
            send(mailSender,mail);
        } catch (MailException e) {
            LOGGER.error("\n发件人：{}\n" + "收件人：{}\n" + "邮件主题：{}\n" + "结果: {}\n" + "失败原因：{}",
                    mail.getFrom(),mail.getTo(),mail.getSubject(),CoreConstant.FAIL,e.getMessage());
            throw new CommonException(ResponseEnum.MAIL_SEND_FAIL);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        }
    }

    /**
     * 构建默认发布邮箱
     * */
    private static JavaMailSenderImpl buildJavaMailSenderImpl() throws Exception{
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(HOST);
        javaMailSender.setPort(Integer.valueOf(PORT));
        javaMailSender.setUsername(USERNAME);
        javaMailSender.setPassword(PASSWORD);
        javaMailSender.setDefaultEncoding(DEFAULT_ENCODING);
        javaMailSender.setProtocol(PROTOCOL);
        return javaMailSender;
    }

    /**
     * 自定义发送邮件：自定义发件人
     * */
    public static void sendCustomMail(JavaMailSenderVo javaMailSenderVo,Mail mail){
        JavaMailSenderImpl mailSender = null;
        try {
            mailSender = buildCustomJavaMailSenderImpl(javaMailSenderVo);
            send(mailSender,mail);
        } catch (MailException e) {
            LOGGER.error("\n发件人：{}\n" + "收件人：{}\n" + "邮件主题：{}\n" + "结果: {}\n" + "失败原因：{}",
                    mail.getFrom(),mail.getTo(),mail.getSubject(),CoreConstant.FAIL,e.getMessage());
            throw new CommonException(ResponseEnum.MAIL_SEND_FAIL);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        }
    }

    private static void send(JavaMailSenderImpl mailSender, Mail mail) throws MailException{
        MimeMessage message = buildMessage(mailSender);
        //封装发送邮件格式
        MimeMessageHelper helper = buildMail(message,mail);
        //发送邮件
        mailSender.send(helper.getMimeMessage());
        mail.setResult(CoreConstant.SUCCESS);
        LOGGER.info("\n发件人：{}\n" + "收件人：{}\n" + "邮件主题：{}\n" + "结果: {}",
                mail.getFrom(),mail.getTo(),mail.getSubject(),CoreConstant.SUCCESS);
    }

    /**
     * 构建自定义发布邮箱
     * */
    private static JavaMailSenderImpl buildCustomJavaMailSenderImpl(JavaMailSenderVo mailSenderVo) throws Exception{
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(mailSenderVo.getHost());
        javaMailSender.setPort(mailSenderVo.getPort());
        javaMailSender.setUsername(mailSenderVo.getUsername());
        javaMailSender.setPassword(mailSenderVo.getPassword());
        javaMailSender.setDefaultEncoding(mailSenderVo.getDefaultEncoding());
        javaMailSender.setProtocol(mailSenderVo.getProtocol());
        return javaMailSender;
    }

}
